import { Box, Paper, Typography } from "@mui/material";
import React, { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { toast } from "react-toastify";
import PostForm from "../components/PostForm";
import { createPost, getFriendStyles } from "../services/api";

export default function CreatePost() {
  const [loading, setLoading] = useState(false);
  const [friendStyles, setFriendStyles] = useState([]);

  const navigate = useNavigate();

  useEffect(() => {
    const fetchFriendStyles = async () => {
      try {
        const response = await getFriendStyles();
        setFriendStyles(response.result);
      } catch (error) {
        console.error("Failed to fetch friend styles:", error);
        toast.error("Failed to fetch friend styles. Please try again.");
      }
    };

    fetchFriendStyles();
  }, []);

  const handleSubmit = async (formData) => {
    if (!formData.content) {
      toast.error("Content is required!");
      return;
    }
    if (formData.imageUrls.length < 1) {
      toast.error("Please upload at least one post image!");
      return;
    }

    setLoading(true);
    try {
      const payload = {
        ...formData,
        imageUrls: formData.imageUrls,
      };

      await createPost(payload);
      toast.success("Post created successfully!");
      navigate("/");
    } catch (error) {
      toast.error(error.message || "Failed to create post");
      console.error("Create post error:", error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Box sx={{ p: 3 }}>
      <Paper sx={{ p: 3, maxWidth: 600, margin: "auto" }}>
        <Typography variant="h5" gutterBottom>
          Create New Post
        </Typography>
        {friendStyles.length === 0 ? (
          <>
            <text>Loading...</text>
          </>
        ) : (
          <PostForm
            onSubmit={handleSubmit}
            loading={loading}
            friendStyles={friendStyles}
          />
        )}
      </Paper>
    </Box>
  );
}
